package com.neuedu.wemall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.wemall.common.vo.ResponseData;
import org.springframework.stereotype.Service;
import com.neuedu.wemall.dao.entity.Address;
import com.neuedu.wemall.service.IAddressService;
import com.neuedu.wemall.dao.mapper.AddressMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {
    @Override
    public ResponseData createAddress(Address address) {
        if (StrUtil.isEmpty(address.getRecvName())) {
            return ResponseData.missParam("收件人姓名");
        }
        if (StrUtil.isEmpty(address.getRecvMobile())) {
            return ResponseData.missParam("收件人手机号码");
        }
        if (StrUtil.isEmpty(address.getProvince())) {
            return ResponseData.missParam("省/直辖市");
        }
        if (StrUtil.isEmpty(address.getCity())) {
            return ResponseData.missParam("地级市");
        }
        if (StrUtil.isEmpty(address.getDistrict())) {
            return ResponseData.missParam("区/县级市");
        }
        if (StrUtil.isEmpty(address.getStreet())) {
            return ResponseData.missParam("街道/乡镇");
        }
        if (StrUtil.isEmpty(address.getDetail())) {
            return ResponseData.missParam("详细地址");
        }
        Integer userId = address.getUserId();
        if (userId == null) {
            return ResponseData.missParam("会员ID");
        }
        //查询当前用户有没有默认的收件地址
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("is_default", 1);
        int count = getBaseMapper().selectCount(queryWrapper).intValue();
        if (0 == count) {
            //第一次添加收件地址,强制设置为默认地址
            address.setIsDefault(1);
            int rows = getBaseMapper().insert(address);
            return ResponseData.success(rows);
        }
        int isDefault = address.getIsDefault();
        if (1 == isDefault) {
            return ResponseData.createFail("已存在一个默认地址");
        }
        if (2 != isDefault) {
            return ResponseData.createFail("收件地址状态错误");
        }
        int rows = getBaseMapper().insert(address);
        return ResponseData.success(rows);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public ResponseData modifyAddress(Address address) {
        //允许属性值为null,表示不会更新该字段;但是不允许把字段修改为空文本("")
        if (StrUtil.EMPTY.equals(address.getRecvName())) {
            return ResponseData.modifyFail("不可以将收件人姓名修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getRecvMobile())) {
            return ResponseData.modifyFail("不可以将收件人手机号码修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getProvince())) {
            return ResponseData.modifyFail("不可以将收件地址中的省份修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getCity())) {
            return ResponseData.modifyFail("不可以将收件地址中的城市修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getDistrict())) {
            return ResponseData.modifyFail("不可以将收件地址中的区县修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getStreet())) {
            return ResponseData.modifyFail("不可以将收件地址中的街道或乡镇修改为空文本");
        }
        if (StrUtil.EMPTY.equals(address.getDetail())) {
            return ResponseData.modifyFail("不可以将收件地址中的详细地址修改为空文本");
        }
        Integer addressId = address.getId();
        if (addressId == null) {
            return ResponseData.missParam("地址ID");
        }
        if (getById(addressId) == null) {
            return ResponseData.modifyFail("地址不存在已被删除");
        }
        Integer userId = address.getUserId();
        if (userId == null) {
            return ResponseData.modifyFail("缺少会员用户ID");
        }

        Integer isDefault = address.getIsDefault();
        if (!(isDefault == null || 1 == isDefault || 2 == isDefault)) {
            return ResponseData.modifyFail("地址状态错误");
        }
        if (isDefault == null) {
            int rows = updateAddress(address);
            return ResponseData.success(rows);
        }
        //先查询出收件地址表中当前的默认地址
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Address::getUserId, userId);
        lqw.eq(Address::getIsDefault, 1);
        Address defaultAddress = getBaseMapper().selectOne(lqw);//当前默认地址
        int defaultId = defaultAddress.getId();//当前默认地址ID
        if (defaultId == addressId && 2 == isDefault) {
            return ResponseData.modifyFail("当前地址是唯一的默认地址,不可以修改非默认的地址");
        }
        if (1 == isDefault && defaultId != addressId) {
            //将另外一个默认地址设置为非默认的
            LambdaUpdateWrapper<Address> luw = new LambdaUpdateWrapper<>();
            luw.eq(Address::getId, defaultId);
            luw.set(Address::getIsDefault, 2);
            getBaseMapper().update(luw);
        }
        int rows = updateAddress(address);
        return ResponseData.success(rows);
    }

    /**
     * 根据会员用户ID和地址ID修改收件地址
     *
     * @param address
     * @return
     */
    private int updateAddress(Address address) {
        LambdaUpdateWrapper<Address> luq = new LambdaUpdateWrapper<>();
        luq.eq(Address::getUserId, address.getUserId());
        luq.eq(Address::getId, address.getId());
        address.setUserId(null);//无需修改收件地址所属会员用户
        return getBaseMapper().update(address, luq);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public ResponseData deleteAddress(Integer id, Integer userId) {
        if (id == null) {
            return ResponseData.missParam("地址ID");
        }
        if (userId == null) {
            return ResponseData.missParam("会员用户ID");
        }
        Address address = getById(id);
        if (address == null) {
            return ResponseData.modifyFail("地址不存在已被删除");
        }
        if (!address.getUserId().equals(userId)) {
            return ResponseData.modifyFail("地址所属用户与当前用户不一致");
        }
        if (1 == address.getIsDefault()) {
            return ResponseData.modifyFail("默认地址不可以删除");
        }
        int rows = getBaseMapper().deleteById(id);
        return ResponseData.success(rows);
    }
}